<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px gw-flex-between"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
    <div>
      <el-form-item label="任务名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="推理状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MODEL_EXEC_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </div>
      <el-form-item>
        <el-button @click="resetQuery" plain type="primary">重置</el-button>
        <el-button @click="handleQuery" type="primary">查询</el-button>
        <div class="btn-ml">
          <el-button
            type="primary"
            @click="openForm('create')"
            v-hasPermi="['multiModel:evaluation-task:create']"
          >
            创建任务
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-if="refreshTable"
      :default-expand-all="isExpandAll"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :header-cell-style="{ 'background': '#CCEBE7', 'text-align':'center', 'color': '#585858' }"
      :row-class-name="rowClassName"
      lazy
      row-key="id"
      @expand-change="handleExpandChange"
      :max-height="tableMaxHeight"
      >
      <el-table-column label="序号" type="index" width="60px" align="center" />
      <el-table-column type="expand" width="20px">
        <template #default="{ row }">
          <el-table :data="row.children" :show-header="false" :stripe="true">
            <el-table-column label="id" prop="id" align="center"  width="80px">
              <template #default="scope">
                {{ scope.row.id ? '' : '' }}
              </template>
            </el-table-column>
            <el-table-column label="任务名称" prop="name" align="center" />
            <el-table-column label="模型名称" prop="singleModelName" align="center" />
            <el-table-column label="评测类型" prop="center" align="center" width="100">
              <template #default="scope">
                {{ scope.row.type ? evaluationTypeObj[scope.row.type] : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="状态" align="left" prop="status" min-width="140px">
              <template #default="scope">
                <div :class="['color-status-' + scope.row.status]" >
                  <span class="status-icon"></span>
                  <span>{{ taskStatus[scope.row.status] }}</span>
                  <span v-if="!scope.row.type && scope.row.status" class="ml-12px">
                    <span v-if="[1, 4].includes(scope.row.status)">
                      <span class="status-text">{{ scope.row.finishNum }}</span> 
                      /
                      <span>{{ scope.row.totalNum }} </span>
                    </span>
                    <span v-else>-</span>
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="任务提交时间"
              align="center"
              prop="createTime"
              :formatter="dateFormatter"
              width="180px"
            >
              <template #default="scope">
                {{ scope.row.createTime ? '' : '' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="280px" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="任务名称" prop="name" />
      <el-table-column label="模型名称" align="center" prop="singleModelName">
        <template #default="scope">
          {{ scope.row.singleModelName ? scope.row.singleModelName : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="评测类型" align="center" prop="type" width="100">
        <template #default="scope">
          {{ evaluationTypeObj[scope.row.type] }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="left" prop="status" min-width="140px">
        <template #default="scope">
          <div :class="['color-status-' + scope.row.status]" >
            <span class="status-icon"></span>
            <span>{{ taskStatus[scope.row.status] }}</span>
            <span v-if="!scope.row.type && scope.row.status" class="ml-12px">
              <span v-if="[1, 4].includes(scope.row.status)">
                <span class="status-text">{{ scope.row.finishNum }}</span> 
                /
                <span>{{ scope.row.totalNum }} </span>
              </span>
              <span v-else>-</span>
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="任务提交时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="280px">
        <template #default="scope">
          <el-button
            link
            :type="![1].includes(scope.row.status) ? 'primary' : ''"
            @click="handleStatus(scope.row.id)"
            v-hasPermi="['multiModel:evaluation-task:update']"
            v-show="![1].includes(scope.row.status)"
          >
            推理
          </el-button>
          <el-button
            link
            :type="[1].includes(scope.row.status) ? 'primary' : ''"
            @click="handleTermination(0, scope.row.id)"
            v-hasPermi="['multiModel:evaluation-task:update']"
            v-if="[1].includes(scope.row.status)"
          >
            推理终止
          </el-button>
          <el-button
            link
            :type="[2, 5, 6, 8].includes(scope.row.status) ? 'primary' : ''"
            @click="openJudging(scope.row.id)"
            v-hasPermi="['multiModel:evaluation-task:score']"
            :disabled="![2, 5, 6, 8].includes(scope.row.status)"
            v-show="![4].includes(scope.row.status)"
          >
            评分
          </el-button>
          <el-button
            link
            :type="[4].includes(scope.row.status) ? 'primary' : ''"
            @click="handleTermination(1, scope.row.id)"
            v-hasPermi="['multiModel:evaluation-task:score']"
            v-if="[4].includes(scope.row.status)"
          >
            评分终止
          </el-button>
          <el-button
            link
            type='primary'
            @click="goDetail(scope.row.id)"
          >
            查看结果
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 弹窗: 创建任务 -->
  <CreateEvaluationTask ref="formRef" @success="handleQuery" />
  <!-- 弹窗: 评分 -->
  <JudgingRules  ref="judgingRef" @success="getList" />
  <!-- 终止 -->
  <DelConfirmDialog ref="delConfirmRef" @confirm="deleteConfirm" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE, getDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { EvaluationTaskApi, EvaluationTaskVO } from '@/api/multiModel/evaluationtask'
import CreateEvaluationTask from './createEvaluation.vue'
import JudgingRules from './judgingRules.vue'

/** 评测任务 列表 */
defineOptions({ name: 'EvaluationTask' })

const message = useMessage() // 消息弹窗

const list = ref<EvaluationTaskVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  status: undefined,
})
const queryFormRef = ref() // 搜索的表单
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
/** 查询列表 */
const getList = async () => {
  try {
    const data = await EvaluationTaskApi.getEvaluationTaskPage(queryParams)
    list.value = data.list
    list.value.forEach(l => {
      l.hasChildren = l.type ? true : false
      l.children = []
    })
    refreshTable.value = false
    total.value = data.total
  } finally {
    nextTick(() => {
      refreshTable.value = true
      isExpandAll.value = false
    })
  }
}

const rowClassName = ({ row }) => {
  // 根据条件决定是否显示展开按钮
  return row.hasChildren ? 'show-expand' : 'hide-expand'
}
const taskStatus:object = {
  0: '待推理',
  1: '推理中',
  2: '推理完成',
  3: '推理失败',
  4:  '评分中',
  5: '评分完成',
  6: '评分失败',
  7: '推理终止',
  8: '评分终止'
}

/** 终止按钮操作 */
const delConfirmRef = ref()
const shutdownTaskType = ref(0)
const handleTermination = async (type:number, id: number) => {
  const text = type === 0 ? '是否确定终止推理?' : '是否确定终止评分?'
  shutdownTaskType.value = type
  delConfirmRef.value.open(id, [text], '终止')
}
/** 终止按钮操作 */
const deleteConfirm = async (id: number) => {
  try {
    await EvaluationTaskApi.shutdownTask({ taskId: id, type:shutdownTaskType.value})
    // 刷新列表
    getList()
    message.success(t('成功终止'))
  } catch {}
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
/** 评分规则弹窗 */
const judgingRef = ref()
const openJudging = (id: number) => {
  judgingRef.value.open(id)
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 创建 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
// 推理
const handleStatus = async (id:number) => {
  try {
    await EvaluationTaskApi.getModelInference(id)
    getList()
  } catch (error) {
    message.error('推理失败')
  }
}
/** 详情 */
const router = useRouter() // 路由
const goDetail = (id: number) => {
  router.push({
    path: '/task/detail',
    query: {
      id
    }
  })
}

// 子列表
const handleExpandChange = async (row) => {
  if (!row.hasChildren) return
  if (row.children && row.children.length) return
  try {
    const res = await EvaluationTaskApi.getEvaluationTaskModelStat({ id: row.id })
    row.children = res
  } catch (error) {
    message.error('获取子列表数据失败')
  }
}
const evaluationTypeObj = ref({})
const getTypeObj = () => {
  const dictOptions = getDictOptions(DICT_TYPE.MODEL_EVALUATE_TYPE)
  dictOptions.forEach(dict => {
    evaluationTypeObj.value[dict.value] = dict.label
  })
}

const tableMaxHeight = ref('300px'); // 初始高度
// 表格高度
const updateMaxHeight = () => {
  tableMaxHeight.value = document.body.clientHeight - 380 + 'px'; // 假设留出100px其他内容空间
}
window.addEventListener('resize', updateMaxHeight)
/** 初始化 **/
onMounted(() => {
  getList()
  getTypeObj()
  updateMaxHeight()
})
onUnmounted(() => {
  window.removeEventListener('resize', updateMaxHeight)
})
</script>

<style scoped lang="scss">
.el-table {
  :deep(.hide-expand .el-table__expand-column .el-table__expand-icon) {
    display: none;
  }
  :deep(.show-expand .el-table__expand-column .el-table__expand-icon) {
    display: block;
  }
  :deep(.el-table__expanded-cell) {
    padding: 0 !important;
  }
}

</style>